/*
 * Copyright (c) 2021 KaiHong Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chinasoft.controller;

import com.chinasoft.annotation.OperationLog;
import com.chinasoft.bean.vo.KnotVO;
import com.chinasoft.bean.vo.SignUpVO;
import com.chinasoft.bean.vo.UserSubjectVO;
import com.chinasoft.constants.SignUpConstants;
import com.chinasoft.service.SignUpService;
import com.chinasoft.utils.Constants;
import com.chinasoft.utils.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报名模块
 *
 * @author dengtao
 */
@CrossOrigin
@RestController
@RequestMapping("/signUp")
@Api(tags = "报名",description = "报名模块")
public class SignUpController {

    private static final Logger logger = LoggerFactory.getLogger(SignUpController.class);

    /**
     * 未审核，自动取消时间
     */
    private static final int DEFAULT_DAYS = 7;

    @Autowired
    private SignUpService signUpService;

    @ApiOperation(value = "获取登录用户课题及审核信息")
    @GetMapping("/getUserSignUp")
    @OperationLog(action = "课题[查询]", operateType = "query")
    public ResultVO getUserSignUp(String userId) {
        ResultVO resultVo = new ResultVO();
        try {
            //获取登录用户
            List<Map<String,Object>> list=signUpService.getUserSubject(userId);
            if(list.size() > 0){
                String signUpStatus=list.get(0).get("signUpStatus").toString();
                String subjectId=list.get(0).get("subjectId").toString();
                List<Map<String,Object>> signUplist=signUpService.getSubject(subjectId,userId);
                //如果为审核中 判断时间是否超过7天 修改状态跳转至释放项目
                if(SignUpConstants.PAGE_STATUS_SECOND.equals(signUpStatus)){
                    //审核中时对比报名时间修改报名状态
                    List<Map<String,Object>> timeList=signUpService.getSignTime(userId);
                    String signTime=timeList.get(0).get("signTime").toString();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    Date signData =sdf.parse(signTime);
                    logger.info("signTime==="+signData);
                    Date date=new Date();
                    logger.info("date==="+date);
                    int days = (int) ((date.getTime() - signData.getTime()) / (1000*3600*24));
                    if(days >= DEFAULT_DAYS){
                        signUpService.updateSignUpStatus(subjectId,SignUpConstants.PAGE_STATUS_FIFTH,userId);
                        signUplist.get(0).put("count",Integer.parseInt(SignUpConstants.PAGE_STATUS_FOURTH));
                        resultVo.setCode(resultVo.SUCCESS);
                        resultVo.setMsg("查询成功");
                        resultVo.setData(signUplist);
                    }else{
                        if (signUplist.get(0).get("knotImage")!=null && !signUplist.get(0).get("knotImage").equals("")) {
                            String knotImage=signUplist.get(0).get("knotImage").toString();
                            System.err.println("knotImage=="+knotImage);
                            signUplist.get(0).put("count",Integer.parseInt(SignUpConstants.PAGE_STATUS_SECOND));
                            resultVo.setCode(resultVo.SUCCESS);
                            resultVo.setMsg("查询成功");
                            resultVo.setData(signUplist);
                        }else{
                            signUplist.get(0).put("count",Integer.parseInt(SignUpConstants.PAGE_STATUS_FIRST));
                            resultVo.setCode(resultVo.SUCCESS);
                            resultVo.setMsg("查询成功");
                            resultVo.setData(signUplist);
                        }
                    }
                }else if(SignUpConstants.PAGE_STATUS_THRID.equals(signUpStatus)){
                    signUplist.get(0).put("count",Integer.parseInt(SignUpConstants.PAGE_STATUS_FIFTH));
                    resultVo.setCode(resultVo.SUCCESS);
                    resultVo.setMsg("查询成功");
                    resultVo.setData(signUplist);
                }else if(SignUpConstants.PAGE_STATUS_FOURTH.equals(signUpStatus)){
                        signUplist.get(0).put("count",Integer.parseInt(SignUpConstants.PAGE_STATUS_THRID));
                        resultVo.setCode(resultVo.SUCCESS);
                        resultVo.setMsg("查询成功");
                        resultVo.setData(signUplist);
                }else if(SignUpConstants.PAGE_STATUS_FIFTH.equals(signUpStatus)){
                        signUplist.get(0).put("count",Integer.parseInt(SignUpConstants.PAGE_STATUS_FOURTH));
                        resultVo.setCode(resultVo.SUCCESS);
                        resultVo.setMsg("查询成功");
                        resultVo.setData(signUplist);
                }
            }
        } catch (Exception e) {
            resultVo.setCode(resultVo.FAIL);
            resultVo.setMsg(e.getMessage());
        }
        return resultVo;
    }

    @ApiOperation(value = "提交结项申请")
    @PostMapping("/saveKnotImage")
    @OperationLog(action = "审核[编辑]", operateType = "update")
    public ResultVO saveKnotImage(@RequestBody KnotVO knotVO){
        ResultVO resultVo = new ResultVO();
        try {
            signUpService.saveKnotImage(knotVO.getUserId(),knotVO.getKnotImage());
            resultVo.setCode(resultVo.SUCCESS);
            resultVo.setMsg("提交成功");
        } catch (Exception e) {
            resultVo.setCode(resultVo.FAIL);
            resultVo.setMsg(e.getMessage());
            System.err.println(e.getMessage());
        }
        return resultVo;
    }

    @ApiOperation(value = "提交课题信息")
    @PostMapping("/saveSignUp")
    @OperationLog(action = "课题[保存]", operateType = "save")
    public ResultVO saveSignUp(@RequestBody SignUpVO signUpVO){
        ResultVO resultVo = new ResultVO();
        try {
            //查询用户是否已报名
            List<Map<String,Object>> signList=signUpService.getSingnByPhone(signUpVO.getPhoneNumber());
            if(signList.size()>0){
                resultVo.setCode(resultVo.FAIL);
                resultVo.setMsg("您已报名其他项目，每个用户一次只能选一个项目进行报名，请勿重复操作，谢谢！");
                return resultVo;
            }
            signUpService.saveSignUp(signUpVO);
            resultVo.setCode(resultVo.SUCCESS);
            resultVo.setMsg("提交成功");
        } catch (Exception e) {
            resultVo.setCode(resultVo.FAIL);
            resultVo.setMsg(e.getMessage());
            System.err.println(e.getMessage());
        }
        return resultVo;
    }
    @ApiOperation(value = "根据分类获取课题信息")
    @GetMapping("/getSubjectByCategory")
    @OperationLog(action = "课题[查询]", operateType = "query")
    public ResultVO getSubjectByCategory(String project) {
        ResultVO resultVo = new ResultVO();
        try {
            List<Map<String,Object>> list=signUpService.getSubjectByCategory(project);
            for(int i=0;i<list.size();i++){
                String subjectId=list.get(i).get("id").toString();
                //获取关联数据
                List<Map<String,Object>> statusList=signUpService.getStatusBySubjectId(subjectId);
                //获取审核状态,如何不存在则为待审请  为2则为审核中获取报名天数  为3则为已认领
                if(statusList.size() > 0){
                    String signUpStatus=statusList.get(0).get("signUpStatus").toString();
                    if(SignUpConstants.PAGE_STATUS_SECOND.equals(signUpStatus)){
                        list.get(i).put("signUpStatus","审核中");
                        //审核中时对比报名时间返回报名天数
                        List<Map<String,Object>> timeList=signUpService.getSignTime(statusList.get(0).get("signUpId").toString());
                        String signTime=timeList.get(0).get("signTime").toString();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        Date signData =sdf.parse(signTime);
                        Date date=new Date();
                        int days = (int) ((date.getTime() - signData.getTime()) / (1000*3600*24));
                        list.get(i).put("Heaven","已报名"+days+"天");
                    }else if(SignUpConstants.PAGE_STATUS_THRID.equals(signUpStatus)){
                        list.get(i).put("signUpStatus","已认领");
                        list.get(i).put("Heaven",null);
                    }else if(SignUpConstants.PAGE_STATUS_FIRST.equals(signUpStatus)){
                        list.get(i).put("signUpStatus","待申请");
                        list.get(i).put("Heaven",null);
                    }else if(SignUpConstants.PAGE_STATUS_FIFTH.equals(signUpStatus)){
                        list.get(i).put("signUpStatus","待申请");
                        list.get(i).put("Heaven",null);
                    }
                }else{
                    list.get(i).put("signUpStatus","待申请");
                    list.get(i).put("Heaven",null);
                }
            }
            resultVo.setData(list);
            resultVo.setCode(resultVo.SUCCESS);
            resultVo.setMsg("查询成功");
        } catch (Exception e) {
            resultVo.setCode(resultVo.FAIL);
            resultVo.setMsg(e.getMessage());
        }
        return resultVo;
    }

    @ApiOperation(value = "根据课题id获取报名者信息")
    @GetMapping("/getSignBySubject")
    @OperationLog(action = "报名信息[查询]", operateType = "query")
    public ResultVO getSignBySubject(String subjectId) {
        ResultVO resultVo = new ResultVO();
        try {
            resultVo.setData(signUpService.getSignBySubject(subjectId));
            resultVo.setCode(resultVo.SUCCESS);
            resultVo.setMsg("查询成功");
        } catch (Exception e) {
            resultVo.setCode(resultVo.FAIL);
            resultVo.setMsg(e.getMessage());
        }
        return resultVo;
    }
    @ApiOperation(value = "更改审核状态")
    @PostMapping("/updateSignUpStatus")
    @OperationLog(action = "审核[编辑]", operateType = "update")
    public ResultVO updateSignUpStatus(@RequestBody UserSubjectVO userSubjectVO){
        ResultVO resultVo = new ResultVO();
        try {
            if(userSubjectVO!=null){
                signUpService.updateSignUpStatus(userSubjectVO.getSubjectId(),userSubjectVO.getSignUpStatus(),userSubjectVO.getUserId());
                resultVo.setCode(resultVo.SUCCESS);
                resultVo.setMsg("修改成功");
            }else{
                resultVo.setCode(resultVo.FAIL);
                resultVo.setMsg("有参数为空");
            }
        } catch (Exception e) {
            resultVo.setCode(resultVo.FAIL);
            resultVo.setMsg(e.getMessage());
            System.err.println(e.getMessage());
        }
        return resultVo;
    }

    @ApiOperation(value = "上传")
    @PostMapping("/uoload")
    @OperationLog(action = "报名信息[上传]", operateType = "uoload")
    public ResultVO uoload(MultipartFile file) throws IOException {
        ResultVO resultVo = new ResultVO();
        String originalFilename = file.getOriginalFilename();
        String filenameWithoutSuffix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String randomFilename =  generateRandomFilename();
        String newFileName = filenameWithoutSuffix + "_" + randomFilename + suffix;
        String imagePathRoot = "/opt/data/autotool/";
        isChartPathExist(imagePathRoot);
        String packagePathUrl = imagePathRoot + newFileName;
        System.err.println("packagePathUrl=="+packagePathUrl);
        write(packagePathUrl,file.getInputStream());
        resultVo.setData(Constants.ROOT_URL+newFileName);
        resultVo.setCode(resultVo.SUCCESS);
        resultVo.setMsg("上传成功");
        return resultVo;
    }
    private static String generateRandomFilename() {
        String RandomFilename = "";
        Random rand = new Random();//生成随机数
        int random = rand.nextInt();
        Calendar calCurrent = Calendar.getInstance();
        int intDay = calCurrent.get(Calendar.DATE);
        int intMonth = calCurrent.get(Calendar.MONTH) + 1;
        int intYear = calCurrent.get(Calendar.YEAR);
        String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
                String.valueOf(intDay) + "_";
        RandomFilename = now + String.valueOf(random > 0 ? random : (-1) * random);
        return RandomFilename;
    }
    public static void isChartPathExist(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
    /**
     * 写入文件
     * @param target
     * @param src
     * @throws IOException
     */
    public static void write(String target, InputStream src) throws IOException {
        OutputStream os = new FileOutputStream(target);
        byte[] buf = new byte[1024];
        int len;
        while (-1 != (len = src.read(buf))) {
            os.write(buf,0,len);
        }
        os.flush();
        os.close();
    }
}
